package org.example.c2;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.TimeUnit;

/**
 * @author liu-rui
 * @date 2020/6/1 下午4:37
 * @description 实践：偏向锁
 * @since
 */
@Slf4j
public class Demo11 {
    public static void main(String[] args) throws InterruptedException {
        log.info(ClassLayout.parseInstance(new Object()).toPrintable());//偏向锁启动有４秒延时，此时还没有生效，所以mark word为001,无锁状态
        TimeUnit.SECONDS.sleep(5);
        final Object lock = new Object();
        log.info(ClassLayout.parseInstance(lock).toPrintable());//等待５秒后，偏向锁功能启动，所以mark word为101

        synchronized (lock) {//同步但是没有竞争，此时使用偏向锁，mark word记录下来线程id
            log.info(ClassLayout.parseInstance(lock).toPrintable());
        }
        log.info("-----");
        synchronized (lock) {//同步但是没有竞争，此时使用偏向锁，mark word记录下来线程id
            log.info(ClassLayout.parseInstance(lock).toPrintable());
        }
        log.info(ClassLayout.parseInstance(lock).toPrintable());//虽然退出了同步块，但是mark word依然是101,mark word仍然保留线程id
        lock.hashCode();//由于调用了hashcode,偏向锁转变为无锁状态,mark word存储hashcode
        log.info(ClassLayout.parseInstance(lock).toPrintable());
    }
}
